function ReadBase64(file: File | Blob, callback: Function): void {
  const reader = new FileReader()

  reader.readAsDataURL(file)

  reader.onload = () => {
    callback(reader.result)
  }
}

export function BlobToFile(blob: Blob, name: string, options?: { type?: string; lastModified?: number }): File {
  return new File([blob], name, options)
}
export function FileToBlob(file: File, options?: { type?: string; endings: "transparent" | "native" }): Blob {
  return new Blob([file], options)
}

export function BlobToBase64(blob: Blob): Promise<string> {
  return new Promise(resolve => {
    ReadBase64(blob, (base64: string) => {
      resolve(base64)
    })
  })
}
export function Base64ToBlob(base64: string): Blob {
  const arr = base64.split(";base64,")
  let str = ""
  let mime = ""
  if (arr.length === 1) str = arr[0]
  else {
    mime = arr[0].split(":")[1]
    str = arr[1]
  }
  const raw = window.atob(str)
  const rawLength = raw.length
  const uint8Array = new Uint8Array(rawLength)

  for (let i = 0; i < rawLength; i++) {
    uint8Array[i] = raw.charCodeAt(i)
  }
  return new Blob([uint8Array], { type: mime })
}

export function FileToBase64(file: File): Promise<string> {
  return new Promise(resolve => {
    ReadBase64(file, (base64: string) => {
      resolve(base64)
    })
  })
}
export function Base64ToFile(base64: string, name: string): File {
  const blob = Base64ToBlob(base64)
  return BlobToFile(blob, name)
}
